/**
 * 指针目标添加接口测试用例
 *
 * Created by snowingsea on 2020/03/07.
 */
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
chai.use(require('chai-http'));
const randomstring = require('randomstring');

const common = require('./../../../common');
const Administrator = require('./../../../../models/administrator');
const uri = require('./../../uri');
const benchmark = require('./../../../../benchmark/analyse-files/logic_bombs');

module.exports = describe('/POST functions/:id/malloc.json', function () {
  const administrator = new Administrator();
  const newUserIds = [];
  let projectVersion = {};
  let func = {};
  function url(functionId) {
    if (!functionId) {
      functionId = func.functionId;
    }
    return `/functions/${functionId}/malloc.json`;
  }

  before(function (done) {
    administrator.login()
      .then(() => administrator.createRandomTester())
      .then((tester) => {
        newUserIds.push(tester.userId);
        return tester.createRandomProject();
      })
      .then((project) => project.createRandomVersion())
      .then((res) => {
        projectVersion = res;
        return projectVersion.getAllFunctions(benchmark);
      })
      .then(([item]) => {
        func = item;
        done();
      })
      .catch(done);
  });
  after(function (done) {
    administrator.removeUsers(newUserIds)
      .then(() => {
        done();
      })
      .catch(done);
  });

  common.should.be.user(uri, url, 'post');
  common.should.be.tester(uri, url, 'post');

  // 正常添加
  [
    { variableName: randomstring.generate({ length: 16, charset: 'alphabetic' }), typeName: 'int' },
    { variableName: randomstring.generate({ length: 16, charset: 'alphabetic' }), elementTypeName: 'char', length: 10 },
  ].forEach((variable, index) => {
    it(`it should ${index === 0 ? 'Add' : 'add'} malloc variable with ${JSON.stringify(variable)}`, function (done) {
      projectVersion.project.creator.login()
        .then(() => {
          chai.request(uri)
            .post(url())
            .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
            .send(variable)
            .end((err, res) => {
              res.should.have.status(200);
              common.should.be.functionMallocVariableMessage(res.body);
              res.body.functionId.should.be.eql(func.functionId);
              res.body.variableName.should.be.eql(variable.variableName);
              if (variable.typeName) {
                res.body.typeName.should.be.eql(variable.typeName);
              } else {
                res.body.elementTypeName.should.be.eql(variable.elementTypeName);
                res.body.length.should.be.eql(variable.length);
              }
              done();
            });
        })
        .catch(done);
    });
  });

  // 缺少参数
  [
    {},
    { variableName: randomstring.generate({ length: 16, charset: 'alphabetic' }) },
    { variableName: randomstring.generate({ length: 16, charset: 'alphabetic' }), elementTypeName: 'int' },
    { variableName: randomstring.generate({ length: 16, charset: 'alphabetic' }), length: 10 },
  ].forEach((variable) => {
    it(`it should fail to add malloc variable with ${JSON.stringify(variable)}`, function (done) {
      projectVersion.project.creator.login()
        .then(() => {
          chai.request(uri)
            .post(url())
            .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
            .send(variable)
            .end((err, res) => {
              res.should.have.status(400);
              common.should.be.errorMessage(res.body);
              done();
            });
        })
        .catch(done);
    });
  });

  // 不可重复添加
  it('it should fail to add malloc variable when the variable is exists', function (done) {
    const variableName = randomstring.generate({ length: 16, charset: 'alphabetic' });
    func.addMallocVariable(variableName, { typeName: 'int' })
      .then(() => projectVersion.project.creator.login())
      .then(() => {
        chai.request(uri)
          .post(url())
          .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
          .send({ variableName, typeName: 'int' })
          .end((err, res) => {
            res.should.have.status(409);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });

  // 不可向不存在的函数添加指针目标
  it('it should fail to add malloc variable when the function is not exists', function (done) {
    new Promise((resolve) => {
      chai.request(uri)
        .post(url('000000000000000000000000'))
        .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
        .send({ variableName: randomstring.generate({ length: 16, charset: 'alphabetic' }), typeName: 'int' })
        .end((err, res) => {
          res.should.have.status(404);
          common.should.be.errorMessage(res.body);
          resolve();
        });
    })
      .then(done)
      .catch(done);
  });

  // 不可向他人项目的函数添加指针目标
  it('it should fail to add malloc variable when the project is not yours', function (done) {
    let newUser;
    administrator.createRandomTester()
      .then((tester) => {
        newUserIds.push(tester.userId);
        newUser = tester;
        return tester.getToken();
      })
      .then(() => {
        chai.request(uri)
          .post(url())
          .set('Authorization', `Bearer ${newUser.token.accessToken}`)
          .send({ variableName: randomstring.generate({ length: 16, charset: 'alphabetic' }), typeName: 'int' })
          .end((err, res) => {
            res.should.have.status(404);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });

  // 不可向冻结的项目版本添加指针变量
  it('it should fail to add malloc variable when the project version is frozen', function (done) {
    projectVersion.project.freezeVersion(projectVersion.versionId)
      .then(() => {
        chai.request(uri)
          .post(url())
          .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
          .send({ variableName: randomstring.generate({ length: 16, charset: 'alphabetic' }), typeName: 'int' })
          .end((err, res) => {
            res.should.have.status(403);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });

  // 不可向冻结的项目添加指针变量
  it('it should fail to add malloc variable when the project is frozen', function (done) {
    projectVersion.project.creator.freezeProject(projectVersion.project.projectId)
      .then(() => {
        chai.request(uri)
          .post(url())
          .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
          .send({ variableName: randomstring.generate({ length: 16, charset: 'alphabetic' }), typeName: 'int' })
          .end((err, res) => {
            res.should.have.status(403);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });
});
